/*
 * Copyright(C) 2019 FUYUN DATA SERVICES CO.,LTD. - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * 该源代码版权归属福韵数据服务有限公司所有
 * 未经授权，任何人不得复制、泄露、转载、使用，否则将视为侵权
 *
 */

import * as React from "react";
import { connect } from "react-redux";
import { IRootState, Dispatch } from "../../../../store";
import { Form, Input, Button, Upload, Icon, Select } from "antd";

import { FormComponentProps } from "antd/lib/form";
import { RcFile } from "antd/lib/upload/interface";

const mapStateToProps = ({ goods, loading }: IRootState) => ({
  goods,
  loading: loading.effects.goods.getProductList as any
});
const mapDispatchToProps = ({ goods }: Dispatch) => ({
  getGoodsList: (payload: any) => goods.getGoodsList(payload),
  uploadGoods: (payload: any) => goods.uploadGoods(payload)
});

type connectedProps = ReturnType<typeof mapStateToProps> &
  ReturnType<typeof mapDispatchToProps>;

interface IState {
  visible: boolean;
  edit: boolean;
  children: any;
  batch: any;
  filedata: any;
  isField: any;
  goodsName: any;
}

interface IProps extends connectedProps {
  loading: boolean;
}

class GoodsPair extends React.Component<IProps & FormComponentProps, IState> {
  public state = {
    visible: false,
    edit: false,
    children: [],
    batch: "",
    filedata: null,
    isField: true,
    goodsName: ""
  };

  public componentDidMount = async () => {
    const { getGoodsList } = this.props;
    await getGoodsList({
      size: "1000000000",
      name: ""
    });

    const { goodsList } = this.props.goods;
    const tempArr: any = [];
    goodsList.map(v => {
      tempArr.push(<Select.Option key={v.id}>{v.name}</Select.Option>);
    });

    this.setState({
      children: tempArr
    });
  };

  public onChangeUpload = (info: any) => {
    console.log(info);
  };

  public beforeUpload = (file: RcFile) => {
    this.setState({
      filedata: file,
      isField: false
    });
    return false;
  };

  public selectedHandle = (values: any) => {
    const { goodsList } = this.props.goods;
    goodsList.map(v => {
      if (v.id === values) {
        this.setState({
          batch: v.productBatch,
          goodsName: v.name
        });
      }
    });
  };

  public selectRemove = (file: RcFile) => {
    this.setState({
      filedata: file,
      isField: true
    });
  };

  public uploadHandle = (e: any) => {
    const { uploadGoods } = this.props;
    const { goodsName } = this.state;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const render = new FileReader();
        render.readAsText(values.file.file);
        let tempstr = "";
        const tempArr: any = [];
        render.onload = function() {
          tempstr = typeof this.result === "string" ? this.result : "";
          tempstr.split("\n").map(v => {
            if (v.trim().length > 0) {
              tempArr.push(v.trim());
            }
          });
          values.qrCodes = tempArr;
          const name = goodsName;
          const batch = values.goodsBatch;
          values.pseudoCode = { goodsName: name, goodsBatch: batch };
          delete values.file;
          delete values.goodsName;
          delete values.goodsBatch;
          uploadGoods(values);
        };
        this.setState({
          visible: false
        });
      }
    });
  };

  public render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="message-container" style={{ paddingTop: 32 }}>
        <Form>
          <Form.Item
            label="商品名称"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 15 }}
          >
            {getFieldDecorator("goodsName", {
              initialValue: "",
              rules: [
                {
                  required: true,
                  message: "请输入商品名称"
                }
              ]
            })(
              <Select onSelect={v => this.selectedHandle(v)}>
                {this.state.children}
              </Select>
            )}
          </Form.Item>

          <Form.Item
            label="商品批次"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 15 }}
          >
            {getFieldDecorator("goodsBatch", {
              initialValue: this.state.batch,
              rules: [
                {
                  required: true,
                  message: "请输入商品批次"
                }
              ]
            })(<Input disabled={true} />)}
          </Form.Item>

          <Form.Item
            label="附件"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 15 }}
          >
            {getFieldDecorator("file", {
              initialValue: "",
              rules: [
                {
                  required: false,
                  message: "请选择附件"
                }
              ]
            })(
              <Upload
                beforeUpload={this.beforeUpload}
                accept=".txt,.TXT"
                onRemove={this.selectRemove}
              >
                <Button disabled={!this.state.isField}>
                  <Icon type="upload" /> 点击上传
                </Button>
              </Upload>
            )}
          </Form.Item>
        </Form>
        <div style={{ textAlign: "center", margin: "20px" }}>
          <Button
            type="primary"
            style={{ marginBottom: "20px" }}
            onClick={this.uploadHandle}
            disabled={this.state.isField}
          >
            保存
          </Button>
        </div>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create<IProps & FormComponentProps>({})(GoodsPair));
